$(document).ready(function() {
    var VAL ={
        NORMAL     : "0000000"  ,
        EVT_USER   : $("#userId").text(),
        T_XPWMSOPE : "XPWMSOPE" ,
        T_XPAPLYWO : "XPAPLYWO"  ,
        T_XPINQBOX : "XPINQBOX",
        T_XPINQCOD : "XPINQCOD",
        T_XPBISOPE : "XPBISOPE"
    };
    var domObj = {
			$window : $(window),
			$ppboxInfoGrdDiv : $("#ppboxInfoGrdDiv"),
			$ppboxInfoGrd : $("#ppboxInfoGrd")
	};
    /**
     * All controls's jquery object/text
     * @type {Object}
     */
    var controlsQuery = {
        W              : $(window)           ,
        destShopSelect : $("#destShopSelect"),
        opeSelect      : $("#opeSelect")     ,
        woIdSelect     : $("#woIdSelect")    ,
        ppBoxIDInput   : $("#ppBoxIDInput")  ,
        shipUserInput  : $("#shipUserInput") ,
        woPlnQtyTxt    : $("#woPlnQtyTxt")   ,
        woWhinQtyTxt   : $("#woWhinQtyTxt")  ,
        woDiffQtyTxt   : $("#woDiffQtyTxt")  ,
        isShipCusTxt   : $("#isShipCusTxt")  ,
        mainGrd   :{
            grdId     : $("#ppboxInfoGrd")   ,
            grdPgText : "#ppboxInfoPg"       ,
            fatherDiv : $("#ppboxInfoGrdDiv")
        }
    };

    /**
     * All button's jquery object
     * @type {Object}
     */
    var btnQuery = {
        del : $('#delete_btn'),
        clr : $('#clear_btn'),
        add : $('#add_btn'),
        regist : $('#regist_btn'),
        query : $('#query_btn')
    };

    /**
     * All tool functions
     * @type {Object}
     */
    var toolFunc = {
        resetJqgrid :function(){
//            controlsQuery.W.unbind("onresize");
//            controlsQuery.mainGrd.grdId.setGridWidth(controlsQuery.mainGrd.fatherDiv.width()*0.80);
//            controlsQuery.W.bind("onresize", this);
        },
        clearInput : function(){
            controlsQuery.ppBoxIDInput.val("");
            controlsQuery.shipUserInput.val("");
            controlsQuery.woPlnQtyTxt.val("");
            controlsQuery.woWhinQtyTxt.val("");
            controlsQuery.woDiffQtyTxt.val("");
        },
        /**
         * 筛选出用户可以操作的仓位 By CMJ
         */
        setDestShopSel : function(){
        	var inObj,outObj;
        	var iary={
        		data_cate : 'DEST',
        		data_ext  : "'E'",
        		user_id   : VAL.EVT_USER
        	};
        	inObj = {
			   trx_id     : 'XPLSTDAT' ,
	           action_flg : 'F'        ,
	           iary       : iary
        	};
        	outObj = comTrxSubSendPostJson(inObj);
        	if(outObj.rtn_code == VAL.NORMAL){
        		_setSelectDate(outObj.tbl_cnt,outObj.oary,"data_id","data_desc","#destShopSelect",true);
        	}
//            addValueByDataCateFnc("#destShopSelect","DEST","data_id", true);
        },
//        iniWoIdSelect : function(){
//            var inObj,
//                outObj;
//            var opeIndex,ope_id,ope_ver;
//            /**
//             * 站点为空时，没有对应可以操作的内部订单。By CMJ
//             */
//            if(!$.trim(controlsQuery.opeSelect.val())){
//                return false;
//            }
//            opeIndex = controlsQuery.opeSelect.val().indexOf("@");
//            ope_id = controlsQuery.opeSelect.val().substr(0, opeIndex);
//            ope_ver = controlsQuery.opeSelect.val().substr(opeIndex+1);
//            
//            inObj = {
//                trx_id      : VAL.T_XPAPLYWO,
//                action_flg  : 'L'           ,
//                iary : {
//                	wo_stats : "'WAIT','CLOS'",
//                    ope_id  : ope_id,
//                    ope_ver : ope_ver
//                }
//            };
//            outObj = comTrxSubSendPostJson(inObj);
//            if (outObj.rtn_code == VAL.NORMAL) {
//                _setSelectDate(outObj.tbl_cnt, outObj.oary, "wo_id", "wo_id", "#woIdSelect", true);
//            }
//        },
        initWoIdSelect : function(){
        	var inObj,
	            outObj;
	        inObj = {
	            trx_id      : VAL.T_XPAPLYWO,
	            action_flg  : 'I'
	        };
	
	        outObj = comTrxSubSendPostJson(inObj);
	        if (outObj.rtn_code == _NORMAL) {
	        	_setSelectDate(outObj.tbl_cnt, outObj.oary, "wo_id", "wo_id", "#woIdSelect", true);
	        }
        },
        getWoInfoFunc : function(){
            var wo_id,
                inObj,
                outObj;

            wo_id = controlsQuery.woIdSelect.val();
            if(!wo_id){
                console.warn("wo_id [%s] is null!", wo_id);
                return false;
            }

            inObj = {
                trx_id      : VAL.T_XPAPLYWO,
                action_flg  : 'Q'           ,
                tbl_cnt     : 1             ,
                iary : {
                    wo_id     : wo_id,
                    mtrl_cate : "SHMT"
                }
            };
            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                controlsQuery.woPlnQtyTxt.val(outObj.oary.pln_prd_qty);
                controlsQuery.woWhinQtyTxt.val(outObj.oary.wip_wh_in_prd_qty);
                controlsQuery.woDiffQtyTxt.val( parseInt(outObj.oary.pln_prd_qty, 10) - parseInt(outObj.oary.wip_wh_in_prd_qty, 10) );
            }
            return true;
        },
        findBoxInGrid : function(){
            var box_id;

            box_id = $.trim(controlsQuery.ppBoxIDInput.val());
            if(!box_id){
                showErrorDialog("","请输入箱号!");
                return false;
            }

            _findRowInGrid('ppboxInfoGrdDiv', controlsQuery.mainGrd.grdId, 'box_id', box_id);
            return true;
        },
        /**
         * 根据人员，厂别，站点的关系，筛选出可以使用的站点。By CMJ
         */
        iniOpeSelect : function(){
            var inObj, outObj;
            var user_id = VAL.EVT_USER;
            var iaryB = {
                user_id     : user_id
            }
            inObj = {
                trx_id      : VAL.T_XPBISOPE,
                action_flg  : 'I',
                iaryB       : iaryB
            };
            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                _setOpeSelectDate(outObj.tbl_cnt, outObj.oary,
                    "ope_id", "ope_ver", "ope_dsc", controlsQuery.opeSelect, true);
            }
        },
        getCurOpe : function(){
            var ope_info,
                ope_info_ary,
                ope_id;

            ope_info = $.trim(controlsQuery.opeSelect.val());

            if(!ope_info){
                return false;
            }

            ope_info_ary = ope_info.split("@");
            ope_id = ope_info_ary[0];

            return ope_id;
        }
    };

    /**
     * All button click function
     * @type {Object}
     */
    var btnFunc = {
        //Clear
        clear_func : function(){
            controlsQuery.mainGrd.grdId.jqGrid("clearGridData");
        },
        //Delete
        del_func : function(){
            var i, j,
                curGrid = controlsQuery.mainGrd.grdId,
                ids = curGrid.jqGrid("getGridParam","selarrrow");
            for ( i = 0, j = ids.length; i < j; i++) {
                curGrid.jqGrid('delRowData', ids[0]);
            }
        },
        //ADD
        add_func : function(){
            var i,j,
                box_id,
                rowIds,
                wo_id,
                dest_shop,
                curRowData,
                curGrid = controlsQuery.mainGrd.grdId;

            box_id = $.trim(controlsQuery.ppBoxIDInput.val());
            if(!box_id){
                showErrorDialog("","请输入箱号");
                return false;
            }

            rowIds = curGrid.jqGrid('getDataIDs');
            if(rowIds){
                for(i = 0, j = rowIds.length; i < j; i++) {
                    curRowData = curGrid.jqGrid('getRowData', rowIds[i]);
                    if(curRowData['box_id'] == box_id){
                        showErrorDialog("",box_id+"已经存在！");
                        return false;
                    }
                }
            }

            inObj = {
                trx_id      : VAL.T_XPINQBOX,
                action_flg  : 'I'           ,
                box_id      : box_id
            };
            wo_id = controlsQuery.woIdSelect.val();
            if(wo_id){
                inObj.wo_id = wo_id;
            }
            dest_shop = controlsQuery.destShopSelect.val();
            if(dest_shop){
                inObj.dest_shop = dest_shop;
            }
        	
            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                if( parseInt( outObj.box_cnt, 10) > 0 ){
                    if( "WAIT" != outObj.box_info.box_stat ){
                        showErrorDialog("","箱子状态为["+ outObj.box_info.box_stat +"],必须为[WAIT]!");
                        return false;
                    }
                    curGrid.jqGrid('addRowData', $.jgrid.randId(), outObj.box_info);
                    toolFunc.clearInput();
                }else{
                    showErrorDialog("","箱子["+ box_id +"]不存在！");
                    return false;
                }
            }
        },
        regist_func : function(){
            var inObj,
                outObj,
                evt_usr, // 送货人
                iary = [],
                ids,
                box_cnt,
                rowData,
                curGrid = controlsQuery.mainGrd.grdId,
                i,j,
                isShipCusChk,
                dest_shop;

            evt_usr = $.trim(controlsQuery.shipUserInput.val());
            if(!evt_usr){
                showErrorDialog("","请输入送货人!");
                return false;
            }

            ids = curGrid.jqGrid("getGridParam","selarrrow");
            box_cnt = ids.length;
            if( box_cnt === 0 ){
                showErrorDialog("","请勾选需要入库的箱号!");
                return false;
            }

            dest_shop = controlsQuery.destShopSelect.val();
            if(!dest_shop){
                showErrorDialog("","请选择仓位");
                return false;
            }

            for( i = 0; i < box_cnt; i++ ){
                rowData = curGrid.jqGrid('getRowData', ids[i]);
                iary.push({
                    box_id : rowData['box_id'],
                    prd_qty : rowData['prd_qty'],
                    wo_id_fk : rowData['wo_id'],
                    dest_shop : dest_shop
                });
            }
            
            isShipCus = controlsQuery.isShipCusTxt[0].checked;
            inObj = {
                trx_id         : VAL.T_XPWMSOPE,
                action_flg     : 'I'           ,
                wip_bank_flg   : 'Y'           ,
                dest_shop      : dest_shop     ,
                evt_user       : VAL.EVT_USER  ,//收货人改为登陆用户
                relate_usr     : evt_usr       ,
                box_cnt        : ids.length    ,
                iary           : iary          ,
                isShipCus      : isShipCus
            };
            outObj = comTrxSubSendPostJson(inObj);
            if(outObj.rtn_code == VAL.NORMAL){
                showSuccessDialog("入库成功！");
                toolFunc.getWoInfoFunc();
            }
        },
        //Query by condition
        query_func : function(){
            var inObj,
                outObj,
                box_id,
                ope_id,
                wo_id,i;

            inObj = {
                trx_id      : VAL.T_XPINQBOX,
                action_flg  : 'I'           ,
                wip_bank_flg  : 'N'         ,
                box_stat    : "WAIT"
            };

            box_id = $.trim(controlsQuery.ppBoxIDInput.val());
            if(box_id){
                inObj.box_id = box_id;
            }
            
            wo_id = controlsQuery.woIdSelect.val();
            if(wo_id){
                inObj.wo_id = wo_id;
            }
            
        	
        	ope_id = toolFunc.getCurOpe();
            if(ope_id){
                inObj.ope_id = ope_id;
            }

            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                setGridInfo(outObj.box_info, "#ppboxInfoGrd");
            }

            return true;
        }
    };

    /**
     * Bind button click action
     */
    var iniButtonAction = function(){
        btnQuery.query.click(function(){
            btnFunc.query_func();
        });
        btnQuery.del.click(function(){
            btnFunc.del_func();
        });
        btnQuery.clr.click(function(){
            btnFunc.clear_func();
        });
        btnQuery.add.click(function(){
            btnFunc.add_func();
        });
        btnQuery.regist.click(function(){
            btnFunc.regist_func();
        });
    };

    /**
     * grid  initialization
     */
    var iniGridInfo = function(){
        var infoCMNew = [
            {name: 'cus_id',      index: 'cus_id',     label: CUS_ID_TAG      , width: CUS_ID_CLM},
            {name: 'so_id',       index: 'so_id',      label: SO_NO_TAG       , width: WO_ID_CLM},
            {name: 'wo_id',       index: 'wo_id',      label: WO_ID_TAG       , width: WO_ID_CLM},
            {name: 'box_id',      index: 'box_id',     label: CRR_ID_TAG      , width: BOX_ID_CLM},
            {name: 'lot_id',      index: 'lot_id',     label: LOT_ID_TAG      , width: LOT_ID_CLM},
            {name: 'prd_qty',     index: 'prd_qty',    label: TOTAL_QTY_TAG   , width: QTY_CLM },

            {name: 'mtrl_prod_id',   index: 'mtrl_prod_id',   label: FROM_MTRL_ID_TAG   , width: MTRL_PROD_ID_CLM},
            {name: 'mdl_id_fk',      index: 'mdl_id_fk',      label: TO_MTRL_ID_TAG     , width: MDL_ID_CLM},
            {name: 'fm_mdl_id_fk',   index: 'fm_mdl_id_fk',   label: FM_MDL_ID_TAG      , width: MDL_ID_CLM},
            {name: 'cut_mdl_id_fk',  index: 'cut_mdl_id_fk',  label: CUT_MDL_ID_TAG     , width: MDL_ID_CLM},
            {name: 'from_thickness', index: 'from_thickness', label: FROM_THICKNESS_TAG , width: QTY_CLM},
            {name: 'to_thickness',   index: 'to_thickness',   label: TO_THICKNESS_TAG   , width: QTY_CLM},

            {name: 'dest_shop' ,  index: 'dest_shop' , label: DEST_SHOP_TAG    , width: DEST_SHOP_CLM },
            {name: 'box_weight',  index: 'box_weight', label: WEIGHT_TAG       , width: QTY_CLM },
            {name: 'box_stat'  ,  index: 'box_stat'  , label: STATUS_TAG       , width: PRD_STAT_CLM},
            {name: 'ok_cnt',  index: 'ok_cnt',  label: OK_CNT_TAG       , width: QTY_CLM },
            {name: 'ng_cnt',  index: 'ng_cnt',  label: NG_CNT_TAG       , width: QTY_CLM },
            {name: 'sc_cnt',  index: 'sc_cnt',  label: SC_CNT_TAG       , width: QTY_CLM },
            {name: 'gk_cnt',  index: 'gk_cnt',  label: GRADE_CONTROL_TAG, width: QTY_CLM },
            {name: 'lz_cnt',  index: 'lz_cnt',  label: GRADE_SCRP_TAG   , width: QTY_CLM }
        ];
        controlsQuery.mainGrd.grdId.jqGrid({
            url:"",
            datatype:"local",
            mtype:"POST",
            height: 360,
            width: 980,
            shrinkToFit:false,
            scroll:true,
            rownumWidth : true,
            resizable : true,
            rowNum:40,
            loadonce:true,
            multiselect : true,
            viewrecords:true,
            pager : controlsQuery.mainGrd.grdPgText,
            fixed: true,
            colModel: infoCMNew
        });
    };

    var shortCutKeyBind = function(){
        document.onkeydown = function(event) {
            if(event.keyCode == F1_KEY){
                btnQuery.query.click();
                return false;
            }else if(event.keyCode == F2_KEY){
                btnQuery.del.click();
                return false;
            }else if (event.keyCode == F3_KEY) {
                btnQuery.clr.click();
                return false;
            }else if (event.keyCode == F4_KEY) {
                btnQuery.add.click();
                return false;
            }else if (event.keyCode == F5_KEY) {
                btnQuery.regist.click();
                return false;
            }

            return true;
        };
    };

    /**
     * Other action bind
     */
    var otherActionBind = function(){
        // Reset size of jqgrid when window resize
        controlsQuery.W.resize(function(){
            toolFunc.resetJqgrid();
        });

        controlsQuery.ppBoxIDInput.keydown(function(event){
            if(event.keyCode === 13){
                toolFunc.findBoxInGrid();
            }
        });

        controlsQuery.woIdSelect.change(function(){
            toolFunc.getWoInfoFunc();
        });
      //Ope select change ==> Wo Id 
        controlsQuery.opeSelect.change(function(){
//            toolFunc.iniWoIdSelect();
        });
        shortCutKeyBind();
    };

    /**
     * Ini view and data
     */
    var initializationFunc = function(){
        iniGridInfo();
        iniButtonAction();
        otherActionBind();
        toolFunc.clearInput();

        //Ini dest shop
        toolFunc.setDestShopSel();

        //Ini ope
        toolFunc.iniOpeSelect();

        //Wo info
        toolFunc.initWoIdSelect();
        toolFunc.getWoInfoFunc();

    };

    initializationFunc();
    function resizeFnc(){                                                                      
    	var offsetBottom, divWidth;                                                              
	
		divWidth = domObj.$ppboxInfoGrdDiv.width();                                   
		offsetBottom = domObj.$window.height() - domObj.$ppboxInfoGrdDiv.offset().top;
		domObj.$ppboxInfoGrdDiv.height(offsetBottom * 0.95);                          
		domObj.$ppboxInfoGrd.setGridWidth(divWidth * 0.99);                   
		domObj.$ppboxInfoGrd.setGridHeight(offsetBottom * 0.99 - 51);               
    };                                                                                         
    resizeFnc();                                                                               
    domObj.$window.resize(function() {                                                         
    	resizeFnc();                                                                             
	}); 
});